<template>
  <section class="main">
    <a-card style="margin-top: 24px" :bordered="false" title="建议">
      <div style="display: flex; justify-content: flex-end; margin-bottom: 20px">
        <a-button type="primary" @click="showDrawer">添加</a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="data"
        style="margin-top: 10px"
        :rowKey="
          (record, index) => {
            return index
          }
        "
        bordered
        @change="
          (pagination, filters, sorter, currentDataSource) =>
            handleTableChange(pagination, filters, sorter, currentDataSource)
        "
        :pagination="ipagination"
      >
        <template
          v-for="col in ['flupDate', 'organization', 'status', 'doctorName', 'receiver']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record, index">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">Save</a>
              <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
                <a>Cancel</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a-button @click="show(index)" style="margin-right: 20px;"> 编辑 </a-button>
              <a-button @click="handleDelete(record)"> 删除 </a-button>
            </span>
          </div>
        </template>
      </a-table>
      <a-modal
        :visible="deleteVisible"
        :confirm-loading="confirmLoading"
        @ok="handleOk2"
        @cancel="handleCancel2"
        width="350px"
      >
        <span>确认要删除该建议吗</span>
      </a-modal>
      <a-drawer
        title="建议"
        :width="720"
        :visible="visible"
        :body-style="{ paddingBottom: '80px' }"
        @close="onClose"
        style="height: 100%; overflow: auto; padding-bottom: 53px"
      >
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="建议类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select
              placeholder="请选择建议类型"
              :disabled="isEdit"
              v-decorator="['signinTypeText', { rules: [{ required: true, message: '请选择建议类型!' }] }]"
            >
              <a-select-option :value="1">血糖</a-select-option>
              <a-select-option :value="2">血压</a-select-option>
              <a-select-option :value="3">运动</a-select-option>
              <a-select-option :value="4">用药</a-select-option>
              <a-select-option :value="5">饮食</a-select-option>
              <a-select-option :value="6">体重</a-select-option>
              <a-select-option :value="7">腰围</a-select-option>
              <a-select-option :value="8">尿酮</a-select-option>
              <a-select-option :value="9">胰岛素</a-select-option>
              <a-select-option :value="10">睡眠</a-select-option>
              <a-select-option :value="13">营养素</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="建议内容" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-textarea
              v-decorator="['suggestContent', { rules: [{ required: true, message: '请输入建议内容！' }] }]"
              :maxLength="100"
              :rows="4"
              placeholder="请输入100字以内的建议内容"
            />
          </a-form-item>
          <div>
            <a
              :style="{ display: 'inline-block', float: 'right', marginRight: '84px', color: 'red' }"
              @click="handleTemplateSave"
            >
              保存到模版
            </a>
            <a
              :style="{ display: 'inline-block', float: 'right', marginRight: '20px', color: 'red' }"
              @click="handleTemplate"
            >
              从模版选择
            </a>
          </div>
          <a-modal
            :visible="saveVisit"
            title="保存到模版"
            ref="saveVisit"
            width="500px"
            @ok="handleOk"
            @cancel="handleCancel"
            :confirm-loading="typeConfirmLoading"
          >
            <a-form-model ref="editform" :model="category" :rules="validatorRules">
              <a-form-model-item label="分类名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 8 }" prop="categoryType">
                <a-select placeholder="请选择分类" v-model="category.categoryType">
                  <a-select-option v-for="item in list" :key="item.dataId" :value="item.dataId">{{
                    item.categoryName
                  }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-form-model>
          </a-modal>
        </a-form>
        <!-- <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
          <a-form-item label="控制目标" style="margin-left: 100px">
            <a-input
              style="width: 50%; margin-bottom: 20px"
              :maxLength="12"
              v-decorator="['recordDate', { rules: [{ required: true, message: '请输入选择记录日期！' }] }]"
              placeholder="请输入记录日期"
            />

            <a-row :gutter="16">
              <a-col :span="24">
                <a-form-item label="建议内容">
                  <a-textarea
                    v-decorator="['suggestContent', { rules: [{ required: true, message: '请输入建议内容！' }] }]"
                    :maxLength="100"
                    :rows="4"
                    v-model="suggestContent"
                    placeholder="请输入100字以内的建议内容"
                  />
                  <div
                    v-if="suggestContent != null && suggestContent.length > 0"
                    :style="{ display: 'inline-block', marginLeft: '12rem' }"
                  >
                    已填写：{{ suggestContent.length }}/100
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form> -->

        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1
          }"
        >
          <a-button :style="{ marginRight: '8px' }" @click="onClose"> 取消 </a-button>
          <a-button type="primary" @click="postAdvise"> 确认 </a-button>
        </div>
      </a-drawer>
    </a-card>
    <advise-template ref="modalForm" @ok="modalFormOk"></advise-template>
  </section>
</template>
<script>
import { postAction, getAction, deleteAction } from '@/api/manage'
import AdviseTemplate from './modules/AdviseTemplate'
import { PAGE_MENU_TYPE } from '@/store/mutation-types'
import { mapGetters } from 'vuex'

const columns = [
  {
    title: '日期',
    dataIndex: 'recordDate',
    width: 120
  },
  {
    title: '建议类型',
    dataIndex: 'signinTypeText',
    width: 120
  },
  {
    title: '建议内容',
    dataIndex: 'suggestContent'
  },
  {
    title: '操作',
    width: 250,
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

const data = []
export default {
  name: 'target',
  components: { AdviseTemplate },
  data() {
    this.cacheData = data.map(item => ({ ...item }))

    return {
      data,
      columns,
      suggestId: '',
      deleteVisible: false,
      confirmLoading: false,
      saveVisit: false,
      category: {},
      typeConfirmLoading: false,
      suggestContent: '',
      recordDate: '',
      dataId: null,
      isEdit: false,
      list: [],
      signinTypeText: '',
      dateFormat: 'YYYY-MM-DD HH:mm:ss',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      pagination1: false,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      visible: false,

      formLayout: 'horizontal',

      url: {
        getAdviseList: '107/01/1070108',
        getTargetValue: '107/02/1070202',
        postAdvise: '107/01/1070107'
      },

      editingKey: '',
      validatorRules: {
        categoryType: [{ required: true, message: '请选择分类' }]
      },
      queryParam: { patientId: this.$route.query[PAGE_MENU_TYPE.PatientId] }
    }
  },
  computed: {},
  created() {
    this.getAdviseList()
    this.getType()
  },
  methods: {
    ...mapGetters(['orgCode', 'orgCode']),
    getType() {
      postAction('/suggest/category/list', { orgCode: this.orgCode() }).then(res => {
        if (res.success) {
          this.list = res.result
        } else {
          console.log(res.message)
        }
      })
    },
    onDateChange(date, dateString) {
      this.recordDate = dateString
    },
    add() {
      this.visible = true
    },
    handleOk() {
      this.$refs.editform.validate(valid => {
        if (valid) {
          const params = {
            patientId: this.queryParam.patientId,
            signinType: this.category.categoryType,
            suggestContent: this.category.suggestContent,
            orgCode: this.orgCode()
          }
          postAction('/201/02/2010219', params).then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.handleCancel()
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      })
    },
    showDrawer() {
      this.cleanForm()
      this.oldWord = this.suggestContent
      this.visible = true
    },
    onClose() {
      this.isEdit = false
      this.visible = false
    },
    handleDelete(record) {
      this.suggestId = record.dataId
      this.deleteVisible = true
    },
    handleCancel2() {
      this.deleteVisible = false
    },
    handleOk2() {
      this.confirmLoading = true
      deleteAction('/107/01/1070111', { suggestId: this.suggestId })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.getAdviseList()
            this.deleteVisible = false
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleTableChange(pagination, filters, sorter, currentDataSource) {
      console.log(pagination)
      this.ipagination = pagination
      this.getAdviseList()
    },
    handleTemplateSave() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.category.suggestContent = values.suggestContent
        }
      })
      this.saveVisit = true
    },
    handleCancel() {
      this.saveVisit = false
    },
    postAdvise() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let params = {
            dataId: this.dataId,
            patientId: this.queryParam.patientId,
            suggestContent: values.suggestContent,
            signinType: values.signinTypeText
          }
          // params.dataId = null
          postAction(this.url.postAdvise, params).then(res => {
            if (res.success) {
              this.$message.success('建议保存成功！')

              this.onClose()
              this.getAdviseList()
            }
          })
        }
      })
    },
    handleTemplate() {
      this.$refs.modalForm.add()
    },
    modalFormOk(content) {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          suggestContent: content
        })
      })
    },
    getAdviseList() {
      this.data = []
      let params = {
        patientId: this.queryParam.patientId,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        period: 0,
        type: 3
      }
      postAction(this.url.getAdviseList, params).then(res => {
        if (res.success) {
          for (let i = 0; i < res.result.records.length; i++) {
            this.data.push({
              dataId: res.result.records[i].dataId || null,
              recordDate: res.result.records[i].recordDate,
              signinTypeText: res.result.records[i].signinTypeText,
              suggestContent: res.result.records[i].suggestContent,
              signinType: res.result.records[i].signinType
            })
          }
          this.ipagination.total = res.result.total
        }
      })
    },

    show(index) {
      this.cleanForm()
      this.dataId = this.data[index].dataId
      this.visible = true
      this.isEdit = true
      this.recordDate = this.data[index].recordDate
      // alert(this.data[index].suggestContent)
      this.$nextTick(() => {
        this.form.setFieldsValue({
          recordDate: this.data[index].recordDate,
          signinTypeText: this.data[index].signinType,
          suggestContent: this.data[index].suggestContent
        })
      })
    },
    cleanForm() {
      this.form.setFieldsValue({
        suggestContent: '',
        signinTypeText: '',
        recordDate: ''
      })
      this.dataId = ''
    },
    handleChange(value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    edit(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
    },
    save(key) {
      const newData = [...this.data]
      const newCacheData = [...this.cacheData]
      const target = newData.filter(item => key === item.key)[0]
      const targetCache = newCacheData.filter(item => key === item.key)[0]
      if (target && targetCache) {
        delete target.editable
        this.data = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    cancel(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = ''
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
        delete target.editable
        this.data = newData
      }
    }
  }
}
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.ant-table-bordered .ant-table-thead > tr > th,
.ant-table-bordered .ant-table-tbody > tr > td {
  text-align: center;
}
.ant-drawer-mask {
  background-color: rgba(0, 0, 0, 0.045);
}
</style>
